using UnityEngine;

public class Viewer : MonoBehaviour
{
    public Camera MainCamera;
    private Vector3 CurrentPosition;
    private Vector3 UpBound;
    private Vector3 DownBound;
    // Start is called before the first frame update
    void Start()
    {
        DownBound = CurrentPosition = MainCamera.transform.position;
        var map = gameObject.GetComponentInParent<GridMap>();
        var ScreenStartPosition = map.StartPos;
        var worldPos = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));
        float upX = ScreenStartPosition.x + map.Width * map.Col - worldPos.x;
        float upY = ScreenStartPosition.y + map.Height * map.Row - worldPos.y;
        if (upX < 0)
            upX = 0;

        if (upY < 0)
            upY = 0;

        UpBound = new Vector3(upX, upY, 100);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            CurrentPosition.y += 0.1f;
            if (CurrentPosition.y > UpBound.y)
            {
                CurrentPosition.y = UpBound.y;
            }
        }

        if (Input.GetKey(KeyCode.A))
        {
            CurrentPosition.x -= 0.1f;
            if (CurrentPosition.x < DownBound.x)
            {
                CurrentPosition.x = DownBound.x;
            }
        }

        if (Input.GetKey(KeyCode.S))
        {
            CurrentPosition.y -= 0.1f;
            if (CurrentPosition.y < DownBound.y)
            {
                CurrentPosition.y = DownBound.y;
            }
        }

        if (Input.GetKey(KeyCode.D))
        {
            CurrentPosition.x += 0.1f;
            if (CurrentPosition.x > UpBound.x)
            {
                CurrentPosition.x = UpBound.x;
            }
        }

        if (MainCamera.transform.position != CurrentPosition)
        {
            MainCamera.transform.position = CurrentPosition;
        }
    }
}
